import { baseURLIp, baseURLProtocol, baseURLPort } from './common'

var kurentoUtils = require('kurento-utils')

export function stopPlay (obj) {
  if (obj.webRtcPeer) {
    obj.webRtcPeer.dispose()
    obj.webRtcPeer = null
    var message = {
      id: 'stop'
    }
    _sendMessage(obj.ws, message)
    obj.ws.close()
    obj.ws = null
  }
}

export function doPalyRtsp (video, rtspUrl, delay, audio) {
  let ret = {}
  let ws = _getWs()
  let webRtcPeer = null
  if (!delay) {
    delay = 50
  }
  ws.onopen = function () {
    let remoteVideo = document.getElementById(video)
    let options = {
      remoteVideo: remoteVideo,
      mediaConstraints: {
        audio: audio
        // video: {
        //   width: 640,
        //   framerate: 15
        // }
      },
      onicecandidate: _tonIceCandidate
    }
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
      function (error) {
        if (error) { return console.error(error) }
        webRtcPeer.generateOffer(_onOffer)
      })
    ret.webRtcPeer = webRtcPeer
    ws.webRtcPeer = webRtcPeer
  }
  ws.onmessage = function (message) {
    let parsedMessage = JSON.parse(message.data)
    switch (parsedMessage.id) {
      case 'startResponse':
        _startResponse(parsedMessage)
        break
      case 'error':
        _onError('Error message from server: ' + parsedMessage.message)
        break
      case 'playEnd':
        // playEnd();
        break
      default:
        break
    }
  }
  ws.onclose = function () {
    console.log('rtsp 后台连接断开.')
  }

  function _onOffer (error, offerSdp) {
    if (error) {
      return console.error(error)
    }
    let message = {
      id: 'start',
      sdpOffer: offerSdp,
      rtspUrl: rtspUrl,
      delay: delay
    }
    _sendMessage(ws, message)
  }

  function _tonIceCandidate (candidate) {
    var message = {
      id: 'onIceCandidate',
      candidate: candidate
    }
    _sendMessage(ws, message)
  }

  function _startResponse (message) {
    webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
      if (error) { return console.error(error) }
    })
  }

  ret.ws = ws
  return ret
}

function _onError (error) {
  console.log(error)
}

function _getWs () {
  let protocol = baseURLProtocol === 'http' ? 'ws' : 'wss'
  return new WebSocket(protocol + '://' + baseURLIp + ':' + baseURLPort + '/player')
}

function _sendMessage (ws, message) {
  var jsonMessage = JSON.stringify(message)
  ws.send(jsonMessage)
}
